<template>
  <div class="login-container">
    <div class="login-form">
      <h2>用户登录</h2>
      
      <!-- 登录方式切换 -->
      <div class="login-tabs">
        <div 
          class="tab" 
          :class="{ active: loginType === 'email' }"
          @click="loginType = 'email'"
        >
          验证码登录
        </div>
        <div 
          class="tab" 
          :class="{ active: loginType === 'emailPwd' }"
          @click="loginType = 'emailPwd'"
        >
          邮箱密码登录
        </div>
      </div>
      
      <form @submit.prevent="handleLogin">
        <!-- 邮箱验证码登录表单 -->
        <div v-if="loginType === 'email'">
          <div class="form-group">
            <label for="email">邮箱</label>
            <input
              type="email"
              id="email"
              v-model="form.email"
              placeholder="请输入邮箱"
              required
            />
          </div>
          <div class="form-group">
            <label for="emailCode">验证码</label>
            <div class="code-input-group">
              <input
                type="text"
                id="emailCode"
                v-model="form.emailCode"
                placeholder="请输入验证码"
                required
              />
              <button 
                type="button" 
                class="code-btn" 
                @click="sendEmailCode"
                :disabled="codeSending || countdown > 0"
              >
                {{ codeSending ? '发送中...' : (countdown > 0 ? `${countdown}s后重发` : '获取验证码') }}
              </button>
            </div>
          </div>
        </div>
        
        <!-- 邮箱密码登录表单 -->
        <div v-if="loginType === 'emailPwd'">
          <div class="form-group">
            <label for="emailPwd">邮箱</label>
            <input
              type="email"
              id="emailPwd"
              v-model="form.emailPwd"
              placeholder="请输入邮箱"
              required
            />
          </div>
          <div class="form-group">
            <label for="emailPassword">密码</label>
            <input
              type="password"
              id="emailPassword"
              v-model="form.emailPassword"
              placeholder="请输入密码"
              required
            />
          </div>
        </div>
        
        <div class="form-options">
          <label class="remember-me">
            <input type="checkbox" v-model="form.remember" />
            记住我
          </label>
          <a href="#" class="forgot-password">忘记密码?</a>
        </div>
        <button type="submit" class="login-btn" :disabled="loading">
          {{ loading ? '登录中...' : '登录' }}
        </button>
        <div class="register-tip">
          💡 未注册用户登录会自动创建账号
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { getEmailCode, loginByEmail, loginByEmailPwd, getCurrentUserPermissions } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const loginType = ref('email') // 默认邮箱验证码登录
const codeSending = ref(false)
const countdown = ref(0)
const form = reactive({
  email: '',
  emailCode: '',
  emailPwd: '',
  emailPassword: '',
  remember: false
})

// 发送邮箱验证码
const sendEmailCode = async () => {
  if (!form.email) {
    alert('请输入邮箱')
    return
  }
  
  // 简单的邮箱格式验证
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(form.email)) {
    alert('请输入有效的邮箱地址')
    return
  }
  
  codeSending.value = true
  try {
    const res = await getEmailCode(form.email)
    if (res.code === 200) {
      alert('验证码已发送，请查收邮件')
      startCountdown()
    } else {
      alert(res.message || '发送验证码失败')
    }
  } catch (error) {
    console.error('发送验证码失败:', error)
    alert(error.message || '发送验证码失败，请稍后重试')
  } finally {
    codeSending.value = false
  }
}

// 倒计时
const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const handleLogin = async () => {
  // 验证表单
  if (loginType.value === 'email') {
    if (!form.email || !form.emailCode) {
      alert('请输入邮箱和验证码')
      return
    }
    
    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(form.email)) {
      alert('请输入有效的邮箱地址')
      return
    }
  } else if (loginType.value === 'emailPwd') {
    if (!form.emailPwd || !form.emailPassword) {
      alert('请输入邮箱和密码')
      return
    }
    
    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    if (!emailRegex.test(form.emailPwd)) {
      alert('请输入有效的邮箱地址')
      return
    }
  }

  loading.value = true
  try {
    let res
    if (loginType.value === 'email') {
      // 邮箱验证码登录
      res = await loginByEmail(form.email, form.emailCode)
    } else if (loginType.value === 'emailPwd') {
      // 邮箱密码登录
      res = await loginByEmailPwd(form.emailPwd, form.emailPassword)
    }
    
    console.log('登录响应:', res)
    
    if (res.code === 200) {
      userStore.setToken(res.data.token)
      userStore.setUserInfo(res.data.userInfo)
      // 保存uid值
      let userId = ''
      if (res.data.uid) {
        userId = res.data.uid
        userStore.setUid(res.data.uid)
      } else if (res.data.userInfo && res.data.userInfo.uid) {
        userId = res.data.userInfo.uid
        userStore.setUid(res.data.userInfo.uid)
      }
      
      // 获取用户权限
      if (userId) {
        try {
          const permissionRes = await getCurrentUserPermissions(userId)
          if (permissionRes.code === 200 && permissionRes.data && permissionRes.data.roleList) {
            userStore.setUserRoles(permissionRes.data.roleList)
          }
        } catch (error) {
          console.error('获取用户权限失败:', error)
        }
      }
      
      alert('登录成功')
      // 跳转到首页或之前的页面
      const redirect = router.currentRoute.value.query.redirect || '/'
      router.push(redirect)
    } else {
      // 登录失败，显示错误信息
      alert(res.msg || res.message || '登录失败，请检查输入信息')
    }
  } catch (error) {
    console.error('登录失败:', error)
    alert(error.message || '登录失败，请检查输入信息')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 80vh;
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4edf9 100%);
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(59, 130, 246, 0.15);
  border: 1px solid rgba(224, 242, 254, 0.5);
  position: relative;
  overflow: hidden;
}

.login-form::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="none" stroke="rgba(59,130,246,0.05)" stroke-width="1"/></svg>');
  background-size: 20px 20px;
  opacity: 0.5;
  z-index: 0;
}

.login-form h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #1e40af;
  position: relative;
  z-index: 1;
  font-size: 1.8rem;
}

.login-tabs {
  display: flex;
  margin-bottom: 25px;
  background: rgba(224, 242, 254, 0.3);
  border-radius: 8px;
  padding: 4px;
  position: relative;
  z-index: 1;
}

.tab {
  flex: 1;
  text-align: center;
  padding: 10px 0;
  cursor: pointer;
  border-radius: 6px;
  font-weight: 500;
  color: #64748b;
  transition: all 0.3s ease;
  font-size: 14px;
}

.tab.active {
  background: linear-gradient(135deg, #3b82f6 0%, #0ea5e9 100%);
  color: white;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.2);
}

.form-group {
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #334155;
}

.form-group input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
}

.form-group input:focus {
  border-color: #3b82f6;
  outline: none;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.code-input-group input {
  flex: 1;
}

.code-btn {
  padding: 0 15px;
  background: linear-gradient(135deg, #3b82f6 0%, #0ea5e9 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  min-width: 100px;
}

.code-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
}

.code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  position: relative;
  z-index: 1;
}

.remember-me {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #64748b;
}

.remember-me input {
  margin-right: 5px;
  accent-color: #3b82f6;
}

.forgot-password {
  font-size: 14px;
  color: #3b82f6;
  text-decoration: none;
  transition: color 0.3s ease;
}

.forgot-password:hover {
  color: #1e40af;
  text-decoration: underline;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #3b82f6 0%, #0ea5e9 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 10px rgba(59, 130, 246, 0.3);
  position: relative;
  z-index: 1;
}

.login-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 15px rgba(59, 130, 246, 0.4);
}

.login-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.register-tip {
  text-align: center;
  margin-top: 20px;
  padding: 12px;
  font-size: 14px;
  color: #0369a1;
  background: rgba(224, 242, 254, 0.5);
  border-radius: 8px;
  position: relative;
  z-index: 1;
  border: 1px solid rgba(14, 165, 233, 0.2);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .login-container {
    padding: 15px;
  }
  
  .login-form {
    padding: 25px 20px;
  }
  
  .login-form h2 {
    font-size: 1.6rem;
    margin-bottom: 20px;
  }
  
  .form-group input {
    padding: 10px 12px;
    font-size: 15px;
  }
  
  .code-btn {
    padding: 0 10px;
    font-size: 13px;
    min-width: 90px;
  }
  
  .login-btn {
    padding: 10px;
    font-size: 15px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .login-container {
    padding: 10px;
  }
  
  .login-form {
    padding: 20px 15px;
  }
  
  .login-form h2 {
    font-size: 1.4rem;
    margin-bottom: 15px;
  }
  
  .form-group input {
    padding: 8px 10px;
    font-size: 14px;
  }
  
  .code-btn {
    padding: 0 8px;
    font-size: 12px;
    min-width: 80px;
  }
  
  .login-btn {
    padding: 8px;
    font-size: 14px;
  }
  
  .register-tip {
    font-size: 13px;
    padding: 10px;
  }
}
</style>